package org.cometmi.gwt.chat.server;

import org.apache.log4j.Logger;
import org.cometmi.gwt.chat.shared.Constants;
import org.cometmi.gwt.chat.shared.SenderProxy;
import org.cometmi.gwt.server.annotation.QueueHandler;
import org.cometmi.gwt.server.events.QueueEvent;
import org.cometmi.gwt.server.events.QueueEventHandler;
import org.cometmi.gwt.shared.MiQueue;
import org.cometmi.gwt.shared.MiQueuePool;
import org.cometmi.gwt.shared.exceptions.InvalidArgumentException;
import org.cometmi.gwt.shared.exceptions.NameParseException;
import org.cometmi.gwt.shared.exceptions.NotAllowedQueueException;

@QueueHandler(queueExpression = "org.cometmi.gwt.test.chat.*")
public class ChatQueueEventHandler implements QueueEventHandler
{
	static protected Logger logger = Logger.getLogger(ChatQueueEventHandler.class);

	@Override
	public void onCreate(QueueEvent event)
	{}

	@Override
	public void onDispose(QueueEvent event)
	{
		try
		{
			MiQueue queueName = event.getSourceQueue();
			String userName = queueName.getAttribute("userName", null);

			MiQueuePool qSend = event.getQueuePool("org.cometmi.gwt.test.chat.*");
			SenderProxy proxy = qSend.proxyToObject(SenderProxy.class, Constants.MESSENGER_ID);

			proxy.printMessage(userName + " has left the chat");
		}
		catch (NameParseException e)
		{}
		catch (InvalidArgumentException e)
		{}
		catch (NotAllowedQueueException e1)
		{}
	}

	@Override
	public void onUpdate(QueueEvent event)
	{
		try
		{
			MiQueue queue = event.getSourceQueue();
			String userName = queue.getAttribute("userName", null);

			MiQueuePool qSend = event.getQueuePool("org.cometmi.gwt.test.chat.*");
			SenderProxy proxy = qSend.proxyToObject(SenderProxy.class, Constants.MESSENGER_ID);

			proxy.printMessage(userName + " has joined the chat");
		}
		catch (NameParseException e)
		{}
		catch (InvalidArgumentException e)
		{}
		catch (NotAllowedQueueException e1)
		{}
	}
}
